import React, {FC, useContext, useState} from 'react';
import "./JournalArchiveBrowsing.less";
import JournalDefaultLayout from "@/pages/JournalPage/JournalDetail/commons/JournalDefaultLayout";
import {Button, DatePicker, Empty, Form, Input, Select, Space, Spin} from "antd";
import HxKwNavs from "@/components/HxKwNavs";
import {AppstoreOutlined, CloseOutlined, UnorderedListOutlined} from "@ant-design/icons";
import {JournalDetailContext} from "@/pages/JournalPage/JournalDetail/commons/JournalDetailContext";
import {useRequest} from "ahooks";
import * as API from "@/services";
import classNames from "classnames";
import {HxArticleNormalItem} from "@/components/HxArticleItem";
import {history, Outlet, useLocation} from "umi";
import HxPagination from "@/components/HxPagination";
import {FormattedMessage} from "@@/exports";

interface JournalArchiveBrowsingProps {
}

const JournalArchiveBrowsing: FC<JournalArchiveBrowsingProps> = (props) => {
  const [form] = Form.useForm();
  const {journalPeriodDisplayType, setJournalPeriodDisplayType} = useContext(JournalDetailContext);
  const {journalId} = useContext(JournalDetailContext)
  const location = useLocation();

  const [showEsSearchResult, setShowEsSearchResult] = useState<boolean>(false);

  const esSearchReq = useRequest((p) => API.queryFrontArticlesByEs({
    pageSize: 20,
    periodZ: false,
    ...p,
    //journalIds: [journalId],
  }), {
    manual: true,
  })
  const articles = esSearchReq.data?.data || [];

  return (
    <JournalDefaultLayout>
      <div className={"journal-archive-browsing-container"}>
        <div className={"journal-archive-browsing-search"}>
          <Form
            form={form}
            className={"journal-archive-browsing-search-form"}
            name="horizontal_login"
            layout="inline"
            initialValues={{
              searchCol: "title",
              //dateRange: [dayjs(), dayjs()]
            }}
            onFinish={(values) => {
              esSearchReq.run({
                publicationYears: [values?.dateRange?.[0]?.year(), values?.dateRange?.[1]?.year()],
                searchText: values?.searchText,
              })
              setShowEsSearchResult(true);
            }}
          >
            <Form.Item
              label={null}
              name="dateRange"
              rules={[{required: false}]}
              style={{width: 190}}
            >
              <DatePicker.RangePicker picker="year" placeholder={["开始年限", "结束年限"]}/>
            </Form.Item>
            <Form.Item
              label={null}
              name="searchCol"
              rules={[{required: false}]}
              style={{width: 100}}
            >
              <Select options={[{
                value: "title",
                label: "标题"
              }]}/>
            </Form.Item>
            <Form.Item
              label={null}
              name="searchText"
              rules={[{required: false}]}
            >
              <Input placeholder={"刊内搜索"}/>
            </Form.Item>
            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                >
                  筛选
                </Button>
                <Button
                  htmlType="reset"
                >
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>


        {
          !showEsSearchResult ? (<HxKwNavs
                value={location.pathname}
                onChange={(value) =>
                  history.push({
                    pathname: value,
                  })}
                extra={(
                  <div>
                    {
                      location.pathname.includes("/archive/period") && (
                        <a className={"toggle-journal-period-display-type-btn"} onClick={(e) => {
                          e.preventDefault();
                          setJournalPeriodDisplayType?.(journalPeriodDisplayType === "tree" ? "card" : "tree");
                        }}>
                          {journalPeriodDisplayType === "tree" ? <AppstoreOutlined/> : <UnorderedListOutlined/>}
                        </a>
                      )
                    }
                  </div>
                )}
                items={[
                  {key: `/journal/${journalId}/archive/period`, label: <FormattedMessage id="text.period" />},
                  {key: `/journal/${journalId}/archive/column`, label: <FormattedMessage id="text.column" />},
                ]}
              >
                <Outlet/>
              </HxKwNavs>
            ) :
            (
              <div className={"journal-archive-es-result"}>
                <a className={"close-es-search-result"} onClick={(e) => {
                  e.preventDefault();
                  setShowEsSearchResult(false)
                }}><CloseOutlined/></a>
                <div className={classNames("journal-es-article-list", {"journal-es-article-list-empty": articles.length === 0})}>
                  <Spin spinning={esSearchReq.loading}>

                    {
                      articles.length > 0 ? (
                          articles.map((item, index) => (
                            <HxArticleNormalItem key={item.id} showCover={true} article={item} onArticleChange={(article) => {
                              esSearchReq?.mutate((oldData) => {
                                return {
                                  ...oldData,
                                  data: oldData!.data.map((item) => {
                                    if (item.id === article.id) {
                                      return {
                                        ...article,
                                      }
                                    }
                                    return item;
                                  })
                                } as API.RespPageResult<API.FrontArticle>;
                              })
                            }}/>
                          ))
                        )
                        :
                        <Empty/>
                    }
                    {
                      esSearchReq.data && (
                        <div className={"hx-pagination-wrapper"}>
                          <HxPagination size="default"
                                        total={esSearchReq.data?.total}
                                        current={esSearchReq.data.current}
                                        pageSize={esSearchReq.data.pageSize}
                                        onChange={(pageNum, pageSize) => {
                                          esSearchReq.run({
                                            page: pageNum,
                                            pageSize
                                          })
                                        }}
                          />
                        </div>
                      )
                    }
                  </Spin>
                </div>
              </div>
            )
        }

      </div>

    </JournalDefaultLayout>
  );
};

export default JournalArchiveBrowsing;
